<template>
  <div class="login-modal">
    <div class="mask" @click="close"></div>
    <div class="login-box">
      <img class="close" @click="close" src="@/assets/img/close.png" alt />
      <div>
        <ul class="title">
          <li :class="isshowform ? 'active' : ''" @click="isshowform = true">手机号码登录</li>
          <li style="margin:0 10px;cursor: auto;">|</li>
          <li :class="!isshowform ? 'active' : ''" @click="toshowweixin">微信扫码登录</li>
        </ul>
        <div class="body">
          <div class="form" v-show="isshowform">
            <div class="input-group">
              <input ref="phone" type="text" placeholder="请输入手机号" v-model="phonenum" />
            </div>
            <slide-verify :l="42" :r="20" :w="360" :h="140" @success="onSuccess" @fail="onFail" @refresh="onRefresh"
              :style="{ width: '100%' }" class="slide-box" ref="slideBlock" :slider-text="msg"></slide-verify>
            <div class="input-group code">
              <input type="text" placeholder="请输入短信验证码,验证规则length>=4" v-model="smscode" />
              <div class="btn" :class="isshowcount ? 'has-count' : ''">
                <span v-show="!isshowcount" @click="getsmscode">获取验证码</span>
                <span v-show="isshowcount">{{ count }}s</span>
              </div>
            </div>
            <span @click="tiaoguo" style="cursor: pointer;">跳过滑块验证获取验证码</span>&nbsp; &nbsp; &nbsp; <span @click="denglu"
              style="cursor: pointer;">登录</span>
            <div class="btn" @click="submitlogin">登录</div>
          </div>
          <div class="wx-qrcode" v-show="!isshowform" id="weixin">weixinerweima</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatephonenumber } from "@/utils";
import Cookies from 'js-cookie'

import {
  sendsmsapi,
  phoneloginapi,
  bindphoneapi,
  userprofilesapi
} from "@/request/api";
export default {
  data() {
    return {
      isshowform: true,
      msg: "向右滑动",
      phonenum: "18510089741",
      isshowcount: false,
      count: 60,
      smscode: ""
    };
  },
  mounted() { },
  methods: {
    verifyfn() {
      if (!validatephonenumber(this.phonenum)) {
        this.aysncchanisshowtoast({
          msg: "请输入正确的手机号码",
          type: "warning"
        });
        this.$refs.phone.focus();
        return false;
      }
      if (this.msg === "再试一次" || this.msg === "向右滑动") {
        this.aysncchanisshowtoast({
          msg: "请滑动滑块到指定位置",
          type: "warning"
        });
        return false;
      }
      return true;
    },
    countdown() {
      let timer = setInterval(() => {
        this.count--;
        if (this.count === 0) {
          clearInterval(timer);
          this.isshowcount = false;
          this.count = 60;
        }
      }, 1000);
    },
    ...mapMutations({
      chanisShowLoginModal: "showLoginModal/chanisShowLoginModal",
      chanislogined: "loginstatus/chanislogined"
    }),
    ...mapActions({
      asyncchanuserinfo: "userinfo/asyncchanuserinfo",
      aysncchanisshowtoast: "showtoast/aysncchanisshowtoast"
    }),
    close() {
      this.chanisShowLoginModal(false);
    },
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success,耗时" + ms + "s";
    },
    onFail() {
      this.onRefresh();
    },
    onRefresh() {
      this.msg = "再试一次";
    },
    async denglu() {
      const code = this.smscode.trim();

      // if (!this.verifyfn()) {
      //   return;
      // }
      if (code.length < 4) {
        // alert('请输入短信验证码!')
        this.aysncchanisshowtoast({
          msg: "短信验证码错误",
          type: "warning"
        });
        return;
      }
      // alert('通过验证，发送登录请求')
      //      this.aysncchanisshowtoast({
      //   msg: '通过验证，发送登录请求',
      //   type: 'success'
      // })
      let uuid = Cookies.get("uuid");
      let res = null;
      if (uuid) {
        let res = await bindphoneapi({
          phone: this.phonenum.trim(),
          verifycode: this.smscode.trim(),
          uuid
        });
      } else {
        // console.log("发送手机号登录请求");
        let res = await phoneloginapi({
          verifyCode: this.smscode.trim(),
          phone: this.phonenum.trim()
        });
        // console.log("res:", res);
        if (!res) return;
        // alert('登录成功')
        this.aysncchanisshowtoast({
          msg: "登录成功，cookie有效期为60s",
          type: "success"
        });
        this.close();

        let seconds = 60;
        let expires = new Date(new Date() * 1 + seconds * 1000);
        Cookies.set('x-auth-token', res["x-auth-token"], { expires: expires }); // 60 秒后失效

        // localStorage.setItem("x-auth-token", res["x-auth-token"]);
        this.chanislogined(true);
      }
      if (uuid) {
        // localStorage.removeItem("uuid");
        Cookies.remove("uuid");
        this.$router.push(this.$route.path);
      }
      // console.log('执行了登录成功请求用户信息');
      this.asyncchanuserinfo();
    },
    async submitlogin() {
      const code = this.smscode.trim();

      if (!this.verifyfn()) {
        return;
      }
      if (code.length < 4) {
        // alert('请输入短信验证码!')
        this.aysncchanisshowtoast({
          msg: "短信验证码错误",
          type: "warning"
        });
        return;
      }
      // alert('通过验证，发送登录请求')
      //      this.aysncchanisshowtoast({
      //   msg: '通过验证，发送登录请求',
      //   type: 'success'
      // })
      let uuid = Cookies.get("uuid");
      let res = null;
      if (uuid) {
        let res = await bindphoneapi({
          phone: this.phonenum.trim(),
          verifycode: this.smscode.trim(),
          uuid
        });
      } else {
        // console.log("发送手机号登录请求");
        let res = await phoneloginapi({
          verifyCode: this.smscode.trim(),
          phone: this.phonenum.trim()
        });
        // console.log("res:", res);
        if (!res) return;
        // alert('登录成功')
        this.aysncchanisshowtoast({
          msg: "登录成功，cookie有效期为60s",
          type: "success"
        });
        this.close();

        let seconds = 10;
        let expires = new Date(new Date() * 1 + seconds * 1000);
        Cookies.set('x-auth-token', res["x-auth-token"], { expires: expires }); // 10 秒后失效

        // localStorage.setItem("x-auth-token", res["x-auth-token"]);
        this.chanislogined(true);
      }
      if (uuid) {
        Cookies.remove("uuid");
        this.$router.push(this.$route.path);
      }
      // console.log('执行了登录成功请求用户信息');
      this.asyncchanuserinfo();
    },
    async tiaoguo() {
      // if (!this.verifyfn()) {
      //   return;
      // }
      // alert("滑动滑块已经验证通过")
      this.aysncchanisshowtoast({
        msg: "滑动滑块已经验证通过",
        type: "success"
      });
      if (!validatephonenumber(this.phonenum)) {
        this.aysncchanisshowtoast({
          msg: "请输入正确的手机号码",
          type: "warning"
        });
        this.$refs.phone.focus();
        return false;
      }
      let res = await sendsmsapi({
        phone: this.phonenum.trim()
      });
      // console.log(res);
      if (!res) return;
      // alert('短信验证码发送成功!')
      this.aysncchanisshowtoast({
        msg: "短信验证码发送成功",
        type: "success"
      });
      this.isshowcount = true;
      this.countdown();
    },
    async getsmscode() {
      if (!this.verifyfn()) {
        return;
      }
      // alert("滑动滑块已经验证通过")
      this.aysncchanisshowtoast({
        msg: "滑动滑块已经验证通过",
        type: "success"
      });
      let res = await sendsmsapi({
        phone: this.phonenum.trim()
      });
      // console.log(res);
      if (!res) return;
      // alert('短信验证码发送成功!')
      this.aysncchanisshowtoast({
        msg: "滑动滑块已经验证通过",
        type: "success"
      });
      this.isshowcount = true;
      this.countdown();
    },
    toshowweixin() {
      this.isshowform = false;
      let _this = this;
      new WxLogin({
        self_redirect: false,
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d",
        scope: "snsapi_login",
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        state:
          "encodeURIComponent(window.btoa('http://127.0.0.1:8080'+_this.$route.path))",
        href:
          "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5paW5mb3sNCiAgICBkaXNwbGF5OiBub25lOw0KDQp9DQouaW1wb3dlckJveCAucXJjb2Rlew0KICAgIHdpZHRoOiAyNDBweDsNCiAgICBtYXJnaW4tdG9wOiAwcHg7DQp9"
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;

  .mask {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%;
  }

  .login-box {
    width: 555px;
    height: 423px;
    position: absolute;
    background-image: url("@/assets/img/login.png");
    margin: auto;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;

    .close {
      position: absolute;
      right: 60px;
      top: 10px;
      cursor: pointer;
    }

    .title {
      display: flex;
      justify-content: center;
      color: #ccc;
      font-size: 18px;
      padding: 45px 0 30px;

      li {
        cursor: pointer;
      }

      .active {
        color: #333;
      }
    }

    .body {
      width: 360px;
      margin: 0 auto;

      .form {
        .input-group {
          display: flex;
          margin-bottom: 20px;

          input {
            height: 50px;
            width: 100%;
            line-height: 50px;
            text-indent: 10px;
            border: 1px solid #ccc;
          }
        }

        .code input {
          width: 260px;
          margin-right: 10px;
        }

        .code .btn {
          flex: 1;
        }

        .btn {
          background-color: #0a328e;
          height: 50px;
          line-height: 50px;
          color: white;
          cursor: pointer;
          text-align: center;
        }

        .has-count {
          background-color: #ccc;
        }
      }
    }
  }
}

::v-deep.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  margin-bottom: 20px;

  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }

  .slide-verify-block {
    width: 85px;
    height: 136px;
  }

  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }

  &:hover {
    canvas {
      display: block;
    }

    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>